local jass = require 'jass.common'
local japi = require 'jass.japi'
local msg  = require 'jass.message'

local mover = { }
setmetatable(mover,mover)
ac.mover.class['point'] = mover

local mt = { }
mover.__index = mt 
extends(ac.mover)(mt)

-- 起始点
mt.start = nil 

-- 目标点
mt.target = nil

-- 弧度
mt.arc = 0.00

-- 速度
mt.speed = 1000

-- 是否旋转倾角
mt.pitch_flag = true 

-- 体积
mt.collision = 0

function mt:init()
    if not self.start then 
        log.error('没有传入起始点')
        return
    end 
    if not self.target then 
        log.error('没有传入目标点')
        return
    end 
    self.start = self.start:get_point()
    -- local object = self.mover
    -- if object.type == 'unit' then 
    --     target.z = target.z + object:get_default_height()
    -- end 
    self.progress = 0
    self.angle = self.start / self.target
    self.distance = self.start * self.target
    self.height = self.max_height or self.start * self.target * self.arc + math.lerp(self.start.z, self.target.z + self.collision, 0.5) 
    self.length = math.sqrt((self.start.z - self.target.z + self.collision) ^ 2 + (self.start * self.target) ^ 2)
    self.moved = 0
    ac.mover.__index.init(self)
end

-- 移动
function mt:move()
    
    local start = self.start 
    local target = self.target
    local angle = self.angle
    local speed = self.speed
    local height = self.height
    local object = self.mover
    if self.length == 0 then
        self:finish()
        return
    end 
    if self.speed <= 0 then 
        self.moved = self.length 
    else
        self.moved = self.moved + self.speed * self.frame
    end 
    local progress = math.min(self.moved / self.length, 1)
    local this_point = object:get_point()
    local next_point = start:lerp( target, progress)
    local this_height = object:get_height()
    local next_height = height and math.parabola( start.z ,height, target.z + self.collision, progress) or math.lerp(start.z,target.z+ self.collision, progress)
    local next_angle = angle
    local next_pacth = ( (progress < 1) and self.pitch_flag) and math.atan( this_height - next_height, math.sqrt( (this_point.x - next_point.x) ^ 2 + (this_point.y - next_point.y) ^ 2 ) ) or 0
    if object.type == 'unit' then 
        next_height = next_height - next_point:get_height()
    end 
    if self:notify ('on_move', next_point, next_height) == false then 
        self:finish()
        return  
    end 
    self:set_point(next_point)
    self:set_height(next_height)
    self:set_rotate(0, next_pacth, next_angle)
    self.progress = progress
    if progress == 1 then 
        self:finish()
    end 
end 

return mover